<?php
// +----------------------------------------------------------------------
// | Description: 用户
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

use think\Db;
use app\admin\model\Common;
use com\verify\HonrayVerify;
class Elesale extends Common
{

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如微信模块用weixin作为数据表前缀
     */
    protected $name = 'user_info';
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $autoWriteTimestamp = DATETIME;
    // protected $insert = [
    //     'status' => 1,
    // ];
  

    public function getosAttr($value)
    {
        if($value == 2) return '其它';
    }


    /**
     * 电销池列表
     * @author cxr <1481746137@qq.com>
     * @param $keywords
     * @param $page
     * @param $limit
     * @param $admin_uid
     * @param $valuedate
     * @param string $os
     * @param string $status
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDataList($keywords, $page, $limit, $admin_uid, $valuedate, $os = '', $status = "")
    {
        $map = [];

        #限制查询几小时前注册的用户
        $day = config('ELE_APPLY_DAY');
        $allowDate = date('Y-m-d H:i:s', strtotime("-{$day}hour"));
        $map['a.create_time'] = ['ELT', $allowDate];

        if ($valuedate) {
            $valuedate = substr($valuedate, 0, 10);
            $valuedate = date('Y-m-d', strtotime("$valuedate +1 day"));
            $map['create_time'] = ['like', '%' . $valuedate . '%'];
        }

        if ($keywords) {
            $map['a.phone|a.name'] = ['like', '%' . $keywords . '%'];
        }
        if ($os) {
            $map['a.os'] = $os;
        }

        # 完成度筛选 屏蔽
        if ($status) {
//            $map += self::getFilter($status);
        }

        #全局
        $map['b.uid'] = ['exp', 'is null'];
        $map['ele_aid'] = ['exp', 'is  null'];

        $listArray = $this
            ->where($map)
            ->field('a.create_time,a.name,a.phone,a.ele_aid,a.id,a.uid')
            ->order('create_time desc,a.id desc')
            ->alias('a')
            ->join('qh_apply b', 'a.uid = b.uid', 'left')
            ->paginate();
        $list = collection ($listArray->items())->toArray();
        foreach($list as $k => $v){

                if(empty($v['name'])){
                    $list[$k]['name'] = Db::name('binvite_about')->where(['uid'=>$v['uid']])->value('name');
                }

            #合并状态信息 屏蔽
//                $status = model('v2/UserInfo')->authStateByInfo($v);
//                $list[$k] += $status;
            $list[$k]['directories'] = 0;
        }

        $data['dataCount'] = $listArray->total();
        $data['list'] = $list;

        return $data;
    }



    /**
     * 获取完成度筛选条件
     * @author cxr <1481746137@qq.com>
     * @param $status 筛选状态
     */
    public static function getFilter($status){
        $map = [];
        switch ($status){
            case '1' : // 银行卡绑定
                $map['a.bank_card_number'] = ['exp','is not null'];
                break;
            case '2' : // 运营商认证
                $map['mongo_operator_report'] = ['exp','is not null and mongo_operator_report != ""'];
                break;
            case '3' : //身份认证
                $map['id_card_img1&id_card_img2&id_card_img3'] = ['exp','is not null'];
                break;
            case '4' : //基本信息
                $map['company&address&zhima&qq&mon_income&wechat_id&payday&zmf&negative_img & job'] = ['exp','is not null'];
                break;
            case '5' : //同步助手
                $map['directories'] = 1;
                break;
            case '6' : //申请
                $map['b.uid'] = ['exp','is not null'];
                break;
            case '7' : //放款
                $map['b.status'] = ['in',[3,4,5,12]];
                break;

        }
        return $map;
    }

    /**
     * 电销认领
     * @author cxr <1481746137@qq.com>
     * @param $id
     * @param $admin_uid
     * @param $uid
     * @return array|bool
     * @throws \think\exception\PDOException
     */
    public function claim($id,$admin_uid,$uid)
    {
         $map['id'] = $id;
         if($this->where($map)->value('ele_aid') > 0)
         {
            return ['code'=>'error','message'=>'已经被认领'];
          
         }

         #认领时判断是否已申请 -。-
        if(Elesalemy::isApply($uid)){
            return ['code'=>'error','message'=>'此用户已经申请'];
        }

         $this->startTrans();
         try{
  
//            $nowdate = date('Y-m-d',time());
//            $mapseq['nowdate'] = ['like','%'.$nowdate.'%'];
//            $infocount = Db::name('claim_seq')
//                         ->where('auth_admin',7)
//                         ->where('admin_id',$admin_uid)
//                         ->where($mapseq)
//                         ->count();
//            $claim_date = ['uid'=>$uid,'apply_id'=>$id,'nowdate'=>$nowdate,'auth_admin'=>7,'seq'=>$infocount+1,'admin_id'=>$admin_uid];
//            Db::name('claim_seq')->insert($claim_date);

             
            $first_claim_date = date('Y-m-d H:i:s',time());
            $data = array('ele_aid'=>$admin_uid,'ele_time'=>$first_claim_date);
            $info = $this->save($data, ['id' => $id]);  //添加至userInfo表中

            // 提交事务
            $this->commit();
            $data = ['code'=>'success','message'=>'认领成功'];
            return $data;
         }catch (\Exception $e) {
              // 回滚事务
            $this->rollback();
            $this->error = '失败';
            return ['code'=>'error','message'=>'认领失败'];
       }

    }



    public function getsexAttr($value)
    {
        $type = [0=>'女',1=>'男',2=>"未知"];
        return $type[$value];
    }

    
    /**
     * [getDataById 根据主键获取详情]
     * @zhanhuiping
     * @DateTime  2017-02-10T21:16:34+0800
     * @param     string                   $id [主键]
     * @return    [array]
     */
    public function getDataById($id = '')
    {

        $data=$this->alias('a')
//            ->join('qh_user_info b','a.uid = b.uid')
//            ->field('a.delay_rate,a.credit_rate*a.period*a.money as rental,a.mobile_type,b.wechat_id,b.city,b.payday,a.bank_card_number,a.name,a.phone,b.age,b.sex,b.qq,b.zhima,b.province,b.id_card_img1,
//                    b.id_card_img2,b.id_card_img3,b.tb_address,b.wx_wallet,b.alipay_bill,
//                    b.wyjt_img,b.wyjt_hk_img,b.open_gid,b.id_card,b.mon_income,b.company,
//                    b.company_ads,a.uid,a.money,a.time,a.check_aid,a.check_time,a.check2_aid,
//                    a.check2_time,a.merchandiser,a.treasurer,a.fk_time,a.hk_time,a.period,
//                    a.appoint_time,a.order_number,a.rate,a.overdue_rate,a.service_rate,
//                    a.procedure_rate,a.credit_rate,a.review,a.remark,b.operator_outUniqueId,a.meets,b.uid,a.upload_img,a.status,b.address,a.return_visit,b.negative_img,b.wechat_img,a.id,a.hang,a.descnote,b.zmf,is_loaning,b.job')
            ->where('a.id',$id)
            ->find();
//            $hang=substr($data['hang'], 0,11);
//            if($hang=='1tolifthang')
//            {
//                $data['hang']=null;
//            }
         $uid = $data['uid'];
//         $data['showlist'] = json_decode($data['meets']);
//         $list = Db::name('admin_condition')->where("status=1 OR uid=$uid")->field('id,content')->select();
         $data['list'] = $list;
        // 初审员
//         $mapa['id'] = $data['check_aid'];
//         $data['check_username'] = Db::name('admin_user')->field('username')->where($mapa)->find();
//
//        //复审员
//        $map1['id'] = $data['check2_aid'];
//        $data['check2_username'] = Db::name('admin_user')->field('username')->where($map1)->find();
//
//        //跟单员
//        $map2['id'] = $data['merchandiser'];
//        $data['merchandiser'] = Db::name('admin_user')->field('username')->where($map2)->find();
//
//        //财务员
//        $map3['id'] = $data['treasurer'];
//        $data['treasurer'] = Db::name('admin_user')->field('username')->where($map3)->find();
//        $map['uid'] = $data['uid'];
//
//        $username = Db::name('user')->where($map)->field('username')->find();
//        $data['username']=$username;
//
//         //历史借款记录
//        $historyrecord = $this->where($map)->field('time,remark,review,time,phone,status,order_number,check_aid,check_time,check2_aid
//          ,check2_time,merchandiser,merchandiser2,treasurer,fk_time,hk_time,money,appoint_time,name,phone,return_visit,refuse_to_lend_money')->select();
//         foreach($historyrecord as $key=>$value)
//         {
//            $map1['id'] = $value['check_aid'];
//            $map2['id'] = $value['check2_aid'];
//            $map3['id'] = $value['merchandiser'];
//            $map4['id'] = $value['treasurer'];
//            $check_aiddata = Db('admin_user')->field('username')->where($map1)->find();
//            $check2_aiddata = Db('admin_user')->field('username')->where($map2)->find();
//            $merchandiserdata = Db('admin_user')->field('username')->where($map3)->find();
//            $treasurerdata = Db('admin_user')->field('username')->where($map4)->find();
//            $historyrecord[$key]['check_aid'] = $check_aiddata['username'];
//            $historyrecord[$key]['check2_aid'] = $check2_aiddata['username'];
//            $historyrecord[$key]['merchandiser'] = $merchandiserdata['username'];
//            $historyrecord[$key]['treasurer'] = $treasurerdata['username'];
//         }
//        // 资料补充
//
//        $datainfo = Db::name('data_supplement')->where($map)->where('is_delete is null')
//                                               ->field('dataname,datacontent,datatime,id,datatype,admin_id')
//                                               ->select();
//
//        foreach($datainfo as $key=>$value)
//        {
//           $where['id'] = $value['admin_id'];
//           $admin_user = Db::name('admin_user')->where($where)->field('username')->find();
//           $datainfo[$key]['datauser'] = $admin_user['username'];
//        }
//
//        $data['historyrecord']=$historyrecord;
//        $data['datainfo']=$datainfo;

      
      
        return $data;
    }
    
    /**
     * 功能:  查询用户名
     * @Author   zhanhuiping
     * @email    18702529695@163.com
     * @DateTime 2017-09-08
     * @return   [type]              [description]
     */
    public function getusername($key,$value)
    {
        
        return $historyrecord;
    }

    /*
    * auth:zhanhuiping
    * date:2017/9/6
    * features:其它驳回恢复
    */
    public function otherdown($param)
    {
      $id = $param['param']['id'];
      $where['id'] = $id;
      $data = ['status'=>0];
      $statusdata = $this->field('status')->where($where)->find();
      if($statusdata['status']!=8)
      {
        $this->error = '状态不为其它驳回';
        return false;
      }
      $info = $this->save($data,$where);
      if(!$info)
      {
         $this->error = '解除失败';
         return false;
      }
      return ture;
    }





    /**
     * 通过id修改用户
     * @param  array   $param  [description]
     */
    public function updateDataById($param, $id)
    {
        $checkData = $this->where('id',$id)->find();

        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }
        if($param['sex']=='男'){
            $param['sex']=1;
        }elseif($param['sex']=='女'){
            $param['sex']=0;
        }
        $validate = validate($this->name);
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }
        $param['update_time']=date('Y-m-d H:i:s',time());;
        $re=$this->allowField(true)->save($param,['id'=>$id]);
        $arr=array();
        $arr['username']=$param['username'];
        $arr['phone']=$param['phone'];
        $re1=Db::name('user')->where('uid',$id)->update($arr);
        if($re || $re1){
            return true;
        }else{
            $this->error = '编辑失败';
            return false;
        }
    }
    public function getName($uid)
    {
        return $this->where('uid',$uid)->value("name");
    }
    public function getPhone($uid)
    {
        return $this->where('uid',$uid)->value("phone");
    }   
    public function getCardNo($no)
    {
        return $this->where('order_number',$no)->value("bank_card_number");
    }
    public function getIdCard($uid)
    {
        return $this->where('uid',$uid)->value("id_card");
    }     
    public function resetDataById($id)
    {
        // 不能操作超级管理员
        if ($id == 1) {
            $this->error = '非法操作';
            return false;
        }
        $checkData = $this->where('uid',$id)->find();
        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }
        /*if($checkData['status']!=1){
            $this->error = '该账户已被删除或禁用！';
            return false;
        }*/
        $param=array();
        $param['password']=123456;
        $param['password'] = user_md5($param['password'],$auth_key = 'qhdkb');
        $param['last_login_time']=date('Y-m-d H:i:s',time());;
        $res=Db::name('user')->where('uid',$id)->update($param);
        if($res){
            return true;
        }else{
            $this->error = '重置失败';
            return false;
        }
    }
    /**
     * 获取所有子孙
     */
    public function getAllChild($id, &$data = [])
    {
        $map['pid'] = $id;
        $childIds = $this->where($map)->column($this->getPk());
        if (!empty($childIds)) {
            foreach ($childIds as $v) {
                $data[] = $v;
                $this->getAllChild($v, $data);
            }
        }
        return $data;
    }
    public function enableData($ids = [], $status = 1, $delSon = false)
    {
        if (empty($ids)) {
            $this->error = '修改失败';
            return false;
        }

        // 查找所有子元素
        if ($delSon && $status === '0') {
            foreach ($ids as $k => $v) {
                $childIds = $this->getAllChild($v);
                $ids = array_merge($ids, $childIds);
            }
            $ids = array_unique($ids);
        }
        $list=$this->where('id','in',$ids)->select();
        $list = modelo2array($list);
        $data['list'] = $list;
        $uids=array();
        foreach($data['list'] as &$v){
            $uids[]=$v['uid'];
        }
        try {
            Db::name('user')->where('uid','in',$uids)->setField('status', $status);
            return true;
        } catch (\Exception $e) {
            $this->error = '操作失败';
            return false;
        }
    }
    
    /**
     * [getInvitDataById 根据主键获取邀请人数详情]
     * @linchuangbin
     * @DateTime  
     * @param     string                   $id [主键]
     * @return    [array]
     */
    public function getInvitDataById($uid,$page, $limit)
    {
        $dataCount = $this->alias('a')
                    ->join('qh_invite_code b','a.uid = b.uid')
                    ->where('puid',$uid)
                    ->count('b.id');
        
        $invitName = $this->where('uid',$uid)->field('name')->find();
        $invitName = json_decode($invitName);
        $list = $this
        ->where(1);
        // 若有分页
        if ($page && $limit) {
            $list = $this->page($page, $limit);
        }
        
        $list=$this->alias('a')
        ->join('qh_invite_code b','a.uid = b.uid')
        ->field('a.name,a.qq,a.phone,a.zhima,b.create_time')
        ->where('b.puid',$uid)
        ->select();
        
        $list = modelo2array($list);
        $data['list'] = $list;
        $data['dataCount'] = $dataCount;
        $data['invitName'] = $invitName;
        return $data;
    }
    /**
     * [getData 获取单条数据]
     * @param  string $field [description]
     * @param  array  $where [description]
     * @return [type]        [description]
     */
    public function getDatas($field = '*',$where = [])
    {
      return $this->field($field)->where($where)->find();
    }

   /**
    *   
    * @param  string $field [description]
    * @param  array  $where [description]
    * @return [type]        [description]
    */
    public function getUserApplyInfo($field = '*',$where = [])
    {
        return $this->alias('a')->field($field)->join('user_info b','a.uid = b.uid',"LEFT")->where($where)->find(); 
    }
    /**
     * [getValue 根据条件获取相关字段]
     * @param  array  $where [description]
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function getValue($where = [], $value = '')
    {
      return $this->where($where)->value($value);
    }

}